/* eslint-disable react/jsx-closing-tag-location */
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { TitleGrid, column } from '../../stores/definitions_refund';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import moment from 'moment';
import RefundPrice from './RefundPrice';
import { areArraysEqual, arrayContrast, computePrice } from '../../stores/method';

const tableId = uniqueId('tauTable-');

const processing = {
  1: t`未处理`,
  2: t`处理中`,
  3: t`已处理`,
};

function OrderRefund({ orderId, ticketCode }) {
  const { busOrderStore: store } = useStore();
  const [orderDetails, setOrderDetails] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [orderRefund] = useState(() => observable({}));
  const [modal, setModal] = useState([]);
  const orderRef = useRef();
  const [processingState, setProcessingState] = useState('');
  const [currentProcessing, setCurrentProcessing] = useState(false);

  const { companies } = global?.getEnvCfg() || {};

  useEffect(() => {
    (async () => {
      if (JSON.stringify(orderId) !== '{}') {
        let orderInfo = [];
        if (ticketCode) {
          const pg = {
            size: 99,
            page: 0,
          };
          orderInfo = await store.getTicket({ ticketCode }, pg);
        } else {
          orderInfo = await store.getIdRefund(orderId);
        }
        setOrderDetails([...orderInfo]);
        // 查询订单  找到每张车票  枚举出中港通那边的处理状态 processingState
        const order = await store.get(orderId);
        const enumerateState = order.busOrder.orderDetails.reduce((acc, item) => {
          if (item?.processingState) {
            acc = item?.processingState;
          }
          return acc;
        }, '');
        setProcessingState(enumerateState);
        setCurrentProcessing((enumerateState === '2') || (enumerateState === '3'));
        editCtx.origin = _.cloneDeep(orderInfo);
        _.assign(orderRefund, orderInfo);
      }
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    if (name === 'refundTime') {
      const diff = moment.duration(moment(orderRefund.busOrder.shift.date).diff(moment(value)));
      const diffStr = `${Math.floor(diff.asHours())}小时${diff.minutes()}分钟${diff.seconds()}秒`;
      _.assign(orderRefund, { distanceTime: diffStr });
    }
    _.set(orderRefund, name, value);

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleRefundCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => handleCancel1?.(),
      });
      return;
    }
    handleCancel1?.();
  };

  // Modal窗口关闭回调
  const handleCancel1 = () => {
    setModal([]);
  };

  const handleOpenEdit = (result) => {
    orderRef.current = result;
    setModal(['refund']);
  };

  const handleCancelRefund = (refund) => {
    const { companyId } = refund?.orderInfo;
    const _type = {};
    if (companies.ZL.id === companyId) {
      _type.content = t`中旅订单不可以取消退款申请, 是否继续?`;
    } else {
      _type.title = t`第三方退票申请处理中`;
      _type.content = (currentProcessing) ? t`第三方专线车票【${processing[processingState]}】, 是否继续 ?` : t`是否继续 ?`;
    }
    Dialog.confirm({
      ..._type,
      onOk: () => cancelRefund(refund),
    });
  };

  async function cancelRefund(refund) {
    await store.orderCancelRefund(refund);
    await init();
  }

  async function init() {
    const orderInfo = await store.getIdRefund(orderId);
    setOrderDetails([...orderInfo]);
  }

  const handleCommitRefund = (refund) => {
    const prices = computePrice(refund);
    const { otherPrice, platformPrice } = prices;
    Dialog.confirm({
      title: t`是否提交该退款申请`,
      content: (<div>
        {(platformPrice !== null) && <span>{t`平台退款: ${platformPrice.toFixed(2)} 元`}</span>}
        <br />
        {(otherPrice !== null) && <span>{t`第三方退款: ${otherPrice.toFixed(2)} 元`}</span>}
      </div>),
      onOk: () => commitRefund(refund),
    });
  };

  async function commitRefund(refund) {
    await store.orderCommitRefund(refund);
    await init();
  }

  // 新增订单数据提交
  const handleOnRefund = async (result, state, type) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        // eslint-disable-next-line no-shadow
        const { id, refundTime, refundPrice, distanceTime, refundRemark = '', orderDetails, attachments } = toJS(result);
        const utcTime = moment.utc(refundTime).toISOString();
        if (store._orderRefundStatus === '0') {
          const orderTicket = orderDetails?.filter((item) => item.check && !item.disabled);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice,
            distanceTime,
            refundRemark,
            attachments: attachments || [],
            ticketRefundInfos: orderTicket,
            state,
            type,
          };
        } else {
          refundArgs = {
            cancelTime: utcTime,
            refundPrice,
            distanceTime,
            refundRemark,
            attachments: attachments || [],
            state,
            type,
          };
        }
        await store.orderSponsorRefund(id, refundArgs);
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败, ${e.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
    // eslint-disable-next-line require-atomic-updates
    await init();
  };

  // 车票二次编辑
  const handleEdit = async (result, refundState, account, otherAccount) => {
    if (!_.isEmpty(result)) {
      try {
        // delete result.orderDetails;
        let argsEdit;
        if (refundState === '0') {
          const numberAccount = account.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          const computeAccount = arrayContrast(open, store.accounts, account);
          argsEdit = {
            ...toJS(result),
            cancelTime: moment.utc(result.cancelTime).subtract(8, 'hours').toISOString(),
          };
          if (!equal) {
            argsEdit.refundPayers = computeAccount;
          }
        } else {
          const numberAccount = otherAccount.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          const computeAccount = arrayContrast(open, store.accounts, account);
          argsEdit = {
            ...toJS(result),
            cancelTime: moment.utc(result.cancelTime).subtract(8, 'hours').toISOString(),
          };
          if (!equal) {
            argsEdit.refundPayers = computeAccount;
          }
        }
        const ticketRefundInfos = argsEdit?.orderDetails?.filter((item) => item.check && !item.disabled) || [];
        await store.orderRefundUpdate({ ...argsEdit, ticketRefundInfos });
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败, ${e.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
    await init();
  };

  return (
    <Form
      inline
      value={orderRefund}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`申请退款记录`} />

      <div className="content">
        <TauTable
          instanceId={tableId}
          // primaryKey="ticketCode"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={orderDetails?.length}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          dataSource={orderDetails}
          hidePagination
          rowKey="applicationId" // 设置每行的唯一标识
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('applicationId', { width: 130 }),
            column('type', {}),
            column('state', {}),
            column('cancelTime', { width: 180 }),
            column('refundTime', { width: 180 }),
            column('refundPrice', {
              width: 188,
              title: t`订单退款金额/第三方金额`,
              cell: (v, i, r) => {
                const { refundInfos = [] } = r;
                const douyin = refundInfos.filter((p) => p.refundChannel !== 'WX');
                const price = douyin.reduce((acc, item) => {
                  const { refundPrice = 0 } = item;
                  acc += refundPrice;
                  return acc;
                }, 0);
                return <span>{`${v.toFixed(2)} / ${price.toFixed(2)}`}</span>;
              },
            }),
            column('cancelRemark', { width: 180 }),
            {
              title: t`操作`,
              width: 200,
              // 非自营公司不可取消
              // https://pm.aspiretop.com/issues/5220
              cell: (_, __, refund) => (
                <>
                  <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleOpenEdit(refund)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" disabled={refund.orderInfo.companyId !== 'platform' || refund.state === '2' || refund.state === '-1'} onClick={() => handleCancelRefund(refund)} >{t`取消`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" disabled={refund.state === '2' || refund.state === '-1'} onClick={() => handleCommitRefund(refund)} >{t`提交申请退款`}</Button>
                </>
              ),
            },
          ]}
        />
      </div>

      <Drawer
        visible={modal[0] === 'refund'}
        title={t`申请退票退款`}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
        }}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="80%"
      >
        <RefundPrice
          modal={modal}
          orderId={orderRef.current}
          onCancel={handleRefundCancel}
          onSubmit={handleOnRefund}
          onEdit={handleEdit}
          isEdit={1}
          frequency={orderDetails?.length}
        />
      </Drawer>
    </Form>
  );
}

export default observer(OrderRefund);

